package service

import (
	"QHMedLink/model"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 1. 创建转让信息（带事务）
func CreateTransfer(db *gorm.DB, transfer *model.OrganizationTransfer) error {
	return db.Transaction(func(tx *gorm.DB) error {
		return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(transfer).Error
	})
}

// 2. 按城市查询（分页）
func GetTransfersByCity(db *gorm.DB, city string, page, size int) ([]model.OrganizationTransfer, error) {
	var transfers []model.OrganizationTransfer
	offset := (page - 1) * size
	if err := db.Where("city = ?", city).
		Offset(offset).Limit(size).
		Order("publish_time DESC").
		Find(&transfers).Error; err != nil {
		return nil, err
	}
	return transfers, nil
}

// 3. 更新转让价格
func UpdateTransferPrice(db *gorm.DB, id uint, newPrice decimal.Decimal) error {
	return db.Model(&model.OrganizationTransfer{}).
		Where("info_id = ?", id).
		Update("transfer_price", newPrice).Error
}

// 4. 复合条件查询（城市+科室+价格区间）
func GetTransfersByConditions(db *gorm.DB, city, dept string, minPrice, maxPrice decimal.Decimal) ([]model.OrganizationTransfer, error) {
	var transfers []model.OrganizationTransfer
	query := db.Where("city = ? AND transfer_price BETWEEN ? AND ?", city, minPrice, maxPrice)
	if dept != "" {
		query = query.Where("department = ?", dept)
	}
	if err := query.Find(&transfers).Error; err != nil {
		return nil, err
	}
	return transfers, nil
}

// 5. 删除转让信息
func DeleteTransfer(db *gorm.DB, id uint) error {
	return db.Model(&model.OrganizationTransfer{}).
		Where("info_id = ?", id).
		Update("is_deleted", true).Error
}
